package com.green.common.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.Logger;

import com.green.common.util.utils.date.DateUtils;

public class DateUtil {
	
	private static final Logger LOGGER = Logger.getLogger(DateUtil.class);

	public static final String DATE_FORMAT_FOR_YMD = "yyyy-MM-dd";
	
	public static final int WEEKS = 7;

	public final  static String DATE_PATTERN = "yyyy-MM-dd";
	public final  static String TIME_PATTERN = "yyyy-MM-dd hh:mm:ss";
	public final  static String TIME_PATTERN_24 = "yyyy-MM-dd HH:mm:ss";
	public final  static String TIME_NUMBER_PATTERN = "yyyyMMddhhmmss";
	public final  static String TIME_NUMBER_PATTERN_S = "yyyyMMddHHmmssssss";
	public final  static String DATE_NUMBER_PATTERN = "yyyyMMdd";
	
	protected static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

	public static String format(Date date, String format) {
		if (date == null) {
			return null;
		}
		DateFormat df = new SimpleDateFormat(format);
		return df.format(date);
	}

	public static Date strToDate(String s, String format) throws Exception {
		DateFormat df = new SimpleDateFormat(format);
		Date d = null;
		try {
			d = df.parse(s);
		} catch (ParseException e) {
			e.printStackTrace();
			throw new Exception("转换成" + format + "日期格式，异常");
		}
		return d;
	}
	
	public static Date strToDate(String s, String format,Date defaultDate) {
		DateFormat df = new SimpleDateFormat(format);
		Date d = null;
		try {
			d = df.parse(s);
		} catch (ParseException e) {
			return defaultDate;
		}
		return d;
	}


	/**
	 * 计算日期 added by taking.wang
	 * 
	 * @param date
	 *            日期
	 * @param month
	 *            月份
	 * @return
	 */
	public static Date calcDate(Date date, int month) throws Exception {
		if (null != date && null != new Integer(month)) { // 先判断当前日期和试用期是否都有数据

			Calendar cal = Calendar.getInstance();
			cal.setTime(date);

			int vYear = cal.get(Calendar.YEAR); // 得到年
			int vMonth = cal.get(Calendar.MONTH) + 1; // 得到月
			int vDay = cal.get(Calendar.DATE); // 得到日

			vMonth += month;
			if (vMonth > 12) { // 如果日期加起来大于12的话，则年份要加1
				vYear++;
				vMonth -= 12;
			}

			return strToDate(vYear + "-" + ((String.valueOf(vMonth).length() == 1) ? "0" + vMonth : vMonth) + "-" + vDay, "yyyy-MM-dd");
		}
		return null;
	}

	/**
	 * d1到d2之间有多少天 比如 5月1号 5月31号有31天
	 * 
	 * @return
	 */
	public static int getDays(Date endDate, Date startDate) {
		return (int) (DateUtils.dayDiff(endDate, startDate) + 1);
	}

	/**
	 * 计算7个工作日后日期
	 * 
	 * @param date
	 * @return
	 */
	public static Date get7WorkDays(Date date) {
		return getNWorkDays(date, 7);
	}

	/**
	 * 获取N个工作日以后的日期
	 * 
	 * @param date
	 * @param n
	 * @return
	 */
	public static Date getNWorkDays(Date date, int n) {
		int week = n / 5;
		int day = n % 5;
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;// 获取这个星期的第几天
		int plusDay = 0;
		if (day_of_week != 0) {// 周日
			int tmp = day_of_week >> 2;// 除以4
			if (tmp == 0) {// 周一到周三，周数乘以7+剩余天数
				plusDay = week * WEEKS + day;
			} else {// 周四到周六，周数乘以7+剩余天数+当周的周六周日两天
				plusDay = week * WEEKS + day + 2;
			}
		} else {
			plusDay = week * WEEKS + day + 1;// 跳过周日本身
		}
		c.add(Calendar.DAY_OF_MONTH, plusDay);

		return c.getTime();
	}

	/**
	 * 
	 * @param date
	 * @param n
	 * @return
	 */
	public static Date getNWorkDaysAgo(Date date, int n) {
		int week = n / 5;// 周数
		int day = n % 5;
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;// 获取这个星期的第几天
		int substactDay = WEEKS * week;
		if (day_of_week > 0 && day_of_week <= 2) {// 周一周二,再去除周六日
			substactDay += day + 2;
		} else if (day_of_week == 0 || day_of_week == 6) {
			substactDay += day + 1;
		} else {
			substactDay += day;
		}
		// 减去相应的时间
		c.add(Calendar.DAY_OF_MONTH, -substactDay);
		return c.getTime();
	}

	/**
	 * 获取7个工作日以前的日期
	 * 
	 * @param date
	 * @return
	 */
	public static Date get7WorkDaysAgo(Date date) {
		return getNWorkDaysAgo(date, 7);
	}

	public static Date parseToCommonDate(String str) throws Exception {
		if (StringUtil.isEmpty(str)) {
			return null;
		}
		return format.parse(str);
	}

	/**
	 * 求两个时间区间的交集天数
	 * 
	 * @param from_1
	 *            区间1开始日期
	 * @param to_1
	 *            区间1结束日期
	 * @param from_2
	 *            区间2开始日期
	 * @param to_2
	 *            区间2结束日期
	 * @param withWeekend
	 *            是否包括周末
	 * @return
	 */
	public static int getDateAreaMix(Date from_1, Date to_1, Date from_2, Date to_2, boolean withWeekend) {
		Calendar start = Calendar.getInstance();
		if (from_1.before(from_2)) {
			start.setTime(from_2);
		} else {
			start.setTime(from_1);
		}
		Calendar end = Calendar.getInstance();
		if (to_1.before(to_2)) {
			end.setTime(to_1);
		} else {
			end.setTime(to_2);
		}
		if (end.before(start)) {
			return 0;
		}
		int count = 0;
		while (end.after(start) || end.equals(start)) {
			if (withWeekend) {
				count++;
			} else {
				if (start.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && start.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
					count++;
				}
			}
			start.add(Calendar.DATE, 1);
		}
		return count;
	}
	
	/**
	 * 得到date-day
	 * @param date
	 * @param day
	 * @return
	 */
	public static Date getDateAfterDay(Date date,int day)
	{
		if(date==null)
		{
			return null;
		}
        Calendar c=Calendar.getInstance();
        c.setTime(new Date(date.getTime()));
	    c.add(Calendar.DAY_OF_YEAR, day);
	    return c.getTime();
	}
	
	/**
	 * 得到一天开始时间
	 * @param date
	 * @return
	 */
	public static Date getStartDate(Date date)
	{
		if(date==null)
		{
			return null;
		}
		 Calendar c=Calendar.getInstance();
	     c.setTime(new Date(date.getTime()));
	     c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), 0, 0, 0);
	     c.set(Calendar.MILLISECOND, 0);
	     return c.getTime();
	}
	
	public static Date getEndDate(Date date)
	{
		if(date==null)
		{
			return null;
		}
		 Calendar c=Calendar.getInstance();
	     c.setTime(new Date(date.getTime()));
	     c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), 23, 59, 59);
	     c.set(Calendar.MILLISECOND, 999);
	     return c.getTime();
	}
	
	/**
	 * 得到一天的开始
	 * @param dateStr
	 * @param format
	 * @return
	 */
	public static Date getStartDate(String dateStr, String format){
		if(dateStr == null){
			return null;
		}
		Date date = null;
		try {
			date = getStartDate(strToDate(dateStr, format));
		} catch (Exception e) {
			LOGGER.error(e, e);
		}
		return date;
	}
	
	/**
	 * 得到一天的结束
	 * @param dateStr
	 * @param format
	 * @return
	 */
	public static Date getEndDate(String dateStr, String format){
		if(dateStr == null){
			return null;
		}
		Date date = null;
		try {
			date = getEndDate(strToDate(dateStr, format));
		} catch (Exception e) {
			LOGGER.error(e, e);
		}
		return date;
	}

	public static void main(String[] args) throws ParseException {
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//		Date from_1 = sdf.parse("2012-07-01");
//		Date to_1 = sdf.parse("2012-07-30");
//		Date from_2 = sdf.parse("2012-07-15");
//		Date to_2 = sdf.parse("2012-07-20");
//		System.out.println(getDateAreaMix(from_1, to_1, from_2, to_2, false));
		System.out.println(DateUtil.format(new Date(), DateUtil.TIME_NUMBER_PATTERN_S));
	}
}
